package com.fled.itsmbigscreen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fled.itsmbigscreen.dto.FindHighBugClient.FindHighBugClientDto;
import com.fled.itsmbigscreen.dto.*;
import com.fled.itsmbigscreen.dto.clientInfoDto.ClientListDto;
import com.fled.itsmbigscreen.dto.clientInfoDto.InfoList;
import com.fled.itsmbigscreen.dto.clientListDto.ClientList;
import com.fled.itsmbigscreen.dto.clientListDto.ClientListData;
import com.fled.itsmbigscreen.dto.groupDto.HuorongBaseList;
import com.fled.itsmbigscreen.enums.HuorongUrlEnums;
import com.fled.itsmbigscreen.mapper.*;
import com.fled.itsmbigscreen.pojo.*;
import com.fled.itsmbigscreen.service.HuorongService;
import com.fled.itsmbigscreen.service.PduService;
import com.fled.itsmbigscreen.utils.HuorongUtils;
import com.fled.itsmbigscreen.utils.PictureUtils;
import com.fled.itsmbigscreen.utils.TimeTool;
import com.fled.itsmbigscreen.vo.GetElectricityByRoomIdVo;
import com.fled.itsmbigscreen.vo.GetSensorByRoomIdVo;
import com.fled.itsmbigscreen.vo.GroupAddVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Service
public class PduServiceImpl implements PduService {

    @Autowired
    private MachineRoomMapper machineRoomMapper;
    @Autowired
    private HuadongPduMapper huadongPduMapper;
    @Autowired
    private PduElectricityMapper pduElectricityMapper;
    @Autowired
    private PduSensorMapper pduSensorMapper;
    @Autowired
    private DeviceAlarmMapper deviceAlarmMapper;
    @Autowired
    JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    String fromEmail;


    /**
     * 获取平均电流电压电能
     *
     * @return
     */
    @Override
    public GetElectricityByRoomIdVo getElectricityByRoomId(Integer roomId) {
//        Boolean  fakeFlag = false;
//        if (roomId!=1){
//            roomId= 1;
//            fakeFlag = true;
//        }
        GetElectricityByRoomIdVo vo = new GetElectricityByRoomIdVo();
        HuadongPduExample huadongPduExample = new HuadongPduExample();
        huadongPduExample.createCriteria().andRoomIdEqualTo(roomId);
        List<HuadongPdu> huadongPdus = huadongPduMapper.selectByExample(huadongPduExample);
        if (huadongPdus != null && huadongPdus.size() > 0) {
            List<Integer> pduIds = new ArrayList<>();
            for (HuadongPdu pdus : huadongPdus) {
                pduIds.add(pdus.getId());
            }
             PduElectricityExample pduElectricityExample = new PduElectricityExample();
            pduElectricityExample.createCriteria().andPduIdIn(pduIds);
            List<PduElectricity> pduElectricities = pduElectricityMapper.selectLastElectricity(pduIds);
//            Map<Integer,PduElectricity> pduElectricityMap = new HashMap<>();
//            for (PduElectricity pduElectricity : pduElectricities) {
//                pduElectricityMap.put(pduElectricity.getPduId(),pduElectricity);
//            }
            double averageCurrent = pduElectricities.stream().mapToDouble(PduElectricity::getCurrent).average().orElse(0D);
            double averageVoltage = pduElectricities.stream().mapToDouble(PduElectricity::getVoltage).average().orElse(0D);
            double averageEnergy = pduElectricities.stream().mapToDouble(PduElectricity::getEnergy).average().orElse(0D);
            vo.setCurrent(TimeTool.kill2(averageCurrent));
//            vo.setVoltage(averageVoltage);
            vo.setVoltage(TimeTool.kill2(averageVoltage));
            vo.setEnergy(TimeTool.kill2(averageEnergy));
            List<PduSensor> pduSensors = pduSensorMapper.selectLast(pduIds,TimeTool.getDayBegin(),TimeTool.getDayEnd());
            double averageHumidity = pduSensors.stream().mapToDouble(PduSensor::getHumidity).average().orElse(0D);
            double averageTemperature = pduSensors.stream().mapToDouble(PduSensor::getTemperature).average().orElse(0D);
            vo.setHumidity(TimeTool.kill2(averageHumidity));
            vo.setTemperature(TimeTool.kill2(averageTemperature));
        }
//        if (fakeFlag){
//            double lowerBound = 0.78; // 指定范围的下限
//            double upperBound = 1.21; // 指定范围的上限
//            double randomValue = lowerBound + Math.random() * (upperBound - lowerBound);
//            vo.setTemperature(TimeTool.kill2(vo.getTemperature()*randomValue));
//            vo.setHumidity(TimeTool.kill2(vo.getHumidity()*randomValue));
//            vo.setVoltage(TimeTool.kill2(vo.getVoltage()*randomValue));
//            vo.setCurrent(TimeTool.kill2(vo.getCurrent()*randomValue));
//            vo.setEnergy(TimeTool.kill2(vo.getEnergy()*randomValue));
//        }

        return vo;
    }

    /**
     * 获取温湿度历史
     *
     * @param roomId
     * @return
     */
    @Override
    public List<GetSensorByRoomIdVo> getSensorByRoomId(Integer roomId) {
//        Boolean  fakeFlag = false;
//        double lowerBound = 0.78; // 指定范围的下限
//        double upperBound = 1.21; // 指定范围的上限
//        double randomValue = lowerBound + Math.random() * (upperBound - lowerBound);
//        if (roomId!=1){
//            roomId= 1;
//            fakeFlag = true;
//        }
        List<GetSensorByRoomIdVo> list = new ArrayList<>();
        HuadongPduExample huadongPduExample = new HuadongPduExample();
        huadongPduExample.createCriteria().andRoomIdEqualTo(roomId);
        List<HuadongPdu> huadongPdus = huadongPduMapper.selectByExample(huadongPduExample);
        if (huadongPdus != null && huadongPdus.size() > 0) {
            List<Integer> pduIds = new ArrayList<>();
            for (HuadongPdu pdus : huadongPdus) {
                pduIds.add(pdus.getId());
            }
//            PduSensorExample pduSensorExample = new PduSensorExample();
//            pduSensorExample.createCriteria().andAddTimeBetween(TimeTool.getDayBegin(), TimeTool.getDayEnd()).andPudIdIn(pduIds);
            List<SelectByExampleGroupMinuteDto> pduSensors = pduSensorMapper.selectByExampleGroupMinute(TimeTool.getDayBegin(), TimeTool.getDayEnd(),pduIds);
            for (SelectByExampleGroupMinuteDto pduSensor : pduSensors) {
                GetSensorByRoomIdVo getSensorByRoomIdVo = new GetSensorByRoomIdVo();
                getSensorByRoomIdVo.setTimeStr(TimeTool.dateFormatOnlyTime(pduSensor.getAddTime()));
                getSensorByRoomIdVo.setHumidity(TimeTool.kill2(pduSensor.getHumidity()));
                getSensorByRoomIdVo.setTemperature(TimeTool.kill2(pduSensor.getTemperature()));
                list.add(getSensorByRoomIdVo);

            }
//            Map<Integer,PduElectricity> pduElectricityMap = new HashMap<>();
//            for (PduElectricity pduElectricity : pduElectricities) {
//                pduElectricityMap.put(pduElectricity.getPduId(),pduElectricity);
//            }
        }
        return list;
    }

    /**
     * 获取告警数
     *
     * @return
     */
    @Override
    public Integer getAlert() {
        DeviceAlarmExample deviceAlarmExample = new DeviceAlarmExample();
        deviceAlarmExample.createCriteria().andAddTimeBetween(TimeTool.getDayBegin(), TimeTool.getDayEnd());
        List<DeviceAlarm> deviceAlarms = deviceAlarmMapper.selectByExample(deviceAlarmExample);
        return deviceAlarms.size();
    }

    /**
     * 获取今日能耗
     *
     * @return
     */
    @Override
    public Double getPower() {
        //获取所有pdu平均能耗
        PduElectricityExample pduElectricityExample = new PduElectricityExample();
        pduElectricityExample.createCriteria().andAddTimeBetween(TimeTool.getDayBegin(), TimeTool.getDayEnd());
        List<PduElectricity> pduElectricities = pduElectricityMapper.selectByExample(pduElectricityExample);
        double averagePower = pduElectricities.stream().mapToDouble(PduElectricity::getEnergy).average().orElse(0D);
        averagePower = TimeTool.kill2(averagePower);
        //距离今天开始过去了几个小时
        long datePoor = TimeTool.getDatePoor(new Date(), TimeTool.getDayBegin());
        Double power = averagePower * datePoor;
        return power;
    }

    @Override
    public void sendMail(String subject,String context) throws MessagingException {
        //发送邮件
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);

        //谁发的
        helper.setFrom(fromEmail);
        //message.setFrom(from+"(abc)");abc将代替from
        //发给谁
        helper.setTo("zhoulichao@fledchina.com");
        //邮件标题
        helper.setSubject(subject);
        //邮件内容
        helper.setText(context,true);

        javaMailSender.send(message);
    }
}
